package com.example.day1203_newsport;


import com.example.day1203_newsport.bean.NewsInfo;
import com.google.gson.Gson;
import ohos.app.Context;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.hiviewdfx.HiLogLabel;
import ohos.net.NetHandle;
import ohos.net.NetManager;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
 * 网络请求
 */
public class NetworkManger {

    private static final HiLogLabel LABEL_LOG = new HiLogLabel(0, 0, "NetworkManger.class");

    private static NetworkManger mInstance;

    EventHandler mEventHandler = new EventHandler(EventRunner.create("NetworkManger"));

    private NetworkManger() {

    }

    public static NetworkManger getInstance() {
        if (mInstance == null) {
            // 当多个线程同时调用时，只能当一个调用完才能被下一个调用
            synchronized (NetworkManger.class) {
                if (mInstance == null) {
                    mInstance = new NetworkManger();
                }
            }
        }

        return mInstance;
    }

    public void requestNewsInfo(Context context, String type, NetworkCallback callback) {
        NetManager netManager = NetManager.getInstance(context);

        if (!netManager.hasDefaultNet()) {
            callback.onFail("当前无网络");
            return;
        }
        mEventHandler.postTask(new Runnable() {
            @Override
            public void run() {
                // 获取当前网络
                NetHandle handle = netManager.getDefaultNet();

                HttpURLConnection connection = null;
                try {

                    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                    String url = "http://v.juhe.cn/toutiao/index?type=" + type + "&key=c9cc35c4e187e4acea9a0c048cc61403";

                    URL url1 = new URL(url);

                    URLConnection urlConnection = handle.openConnection(url1);
                    if (urlConnection instanceof HttpURLConnection) {
                        connection = (HttpURLConnection) urlConnection;
                    }

                    // 请求方式为 获取
                    connection.setRequestMethod("GET");
// 建立连接
                    connection.connect();

                    InputStream inputStream = connection.getInputStream();
                    byte[] bytes = new byte[2 * 1024];
                    int read = inputStream.read(bytes);
                    while (read != -1) {
                        outputStream.write(bytes, 0, read);
                        read = inputStream.read(bytes);
                    }
                    String result = new String(outputStream.toByteArray());

                    if (result ==null){
                        callback.onFail("result is null");
                        return;
                    }

                    Gson gson = new Gson();
                    NewsInfo newsInfo = gson.fromJson(result, NewsInfo.class);

                    context.getUITaskDispatcher().syncDispatch(new Runnable() {
                        @Override
                        public void run() {

                            if (newsInfo.getError_code()==0){
                                callback.onSuccess(newsInfo);
                            } else {
                                callback.onFail(newsInfo.getReason());
                            }

                        }
                    });


                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }


            }
        });


    }


    public interface NetworkCallback {
        void onSuccess(NewsInfo newsInfo);
        void onFail(String result);

    }

}
